import { PlusOutlined } from '@ant-design/icons'
import { Empty, Button } from 'antd'
import { ColumnsType } from 'antd/es/table'
import React, { useEffect, useRef, useState } from 'react'
import { ITableData } from '../types'
import './index.less'
import { arrayMove } from '@dnd-kit/sortable'
import type { DragEndEvent } from '@dnd-kit/core'
import SortableTable from './SortableTable'
interface IProps {
  tableData: any[]
  settableData: React.Dispatch<React.SetStateAction<any[]>>
  columns: ColumnsType<any>
  onSave: (tableData: ITableData[]) => void
  summary?: (data: readonly any[]) => React.ReactNode
  showAddBtn: boolean
  showQuotationEdit: boolean
  showCheckQuotationEdit: boolean
  showMove: boolean
}
export default function EditTable(props: IProps) {
  const tableRef = useRef<HTMLDivElement>(null)
  const [isEditing, setIsEditing] = useState(false)
  const { tableData, settableData, onSave } = props
  const onDragEnd = ({ active, over }: DragEndEvent) => {
    if (active.id !== over?.id) {
      settableData((prevState) => {
        const activeIndex = prevState.findIndex((record) => record.tempId == active?.id)
        const overIndex = prevState.findIndex((record) => record.tempId == over?.id)
        const newdata = arrayMove(prevState, activeIndex, overIndex)
        onSave([...newdata])
        return newdata
      })
    }
  }
  const handleCellClick = (event: any) => {
    if (
      Object.prototype.toString.call(event.target) === '[object SVGSVGElement]' ||
      Object.prototype.toString.call(event.target) === '[object SVGPathElement]'
    ) {
      return
    }
    if (!props.showQuotationEdit && !props.showCheckQuotationEdit) return
    setIsEditing(true)
  }
  const handleClickOutside = (event: any) => {
    if (!props.showQuotationEdit && !props.showCheckQuotationEdit) return
    if (tableRef.current && typeof event?.target?.className == 'string') {
      // 检查点击事件是否发生在当前表格之外，但不是select组件
      if (
        !tableRef.current.contains(event.target) &&
        event?.target?.className?.indexOf('ant-select') == -1 &&
        event?.target?.className?.indexOf('spec_input_drop_down') == -1
      ) {
        // 检查点击事件的路径中是否包含当前表格的引用
        const clickPath = event.path || (event.composedPath && event.composedPath())
        if (!clickPath.includes(tableRef.current)) {
          // 只有当前表格处于编辑状态时才执行保存
          if (isEditing) {
            onSave([...tableData])
            setIsEditing(false) // 重置编辑状态
          }
        }
      }
    }
  }
  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside)
    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [tableData])
  const addData = () => {
    console.log('添加操作')
    tableData.splice(0, 0, {
      tempId: new Date().getTime(),
      isEdit: true,
    })
    settableData([...tableData])
  }
  return (
    <div ref={tableRef} className="quotation_table_container" onClick={handleCellClick}>
      <SortableTable
        rowKey="tempId"
        dataSource={tableData}
        columns={props.columns}
        showMove={props?.showMove}
        onDragEnd={onDragEnd}
        locale={
          props.showAddBtn && {
            emptyText: (
              <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}>
                <Button type="primary" icon={<PlusOutlined />} size="small" onClick={addData} />
              </Empty>
            ),
          }
        }
        summary={props?.summary}
      />
    </div>
  )
}
